package cn.bird.storm.component.sensitive;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.type.MapType;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class SensitiveFieldModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        List<BeanPropertyWriter> newWriters = new ArrayList<>();
        for (BeanPropertyWriter writer : beanProperties) {
            if (writer.getAnnotation(Sensitive.class) != null && writer.getType().isTypeOrSubTypeOf(String.class)) {
                // 如果带有 @Sensitive 注解，并且是字符串，则使用自定义处理
                JsonSerializer<Object> serializer = new SensitiveJsonSerializer(writer.getSerializer());
                if (Objects.isNull(writer.getSerializer())) {
                    writer.assignSerializer(serializer);
                }
            }
            newWriters.add(writer);
        }

        return newWriters;

        // super.changeProperties(config, beanDesc, beanProperties);
    }

    @Override
    public JsonSerializer<?> modifyMapSerializer(SerializationConfig config, MapType valueType, BeanDescription beanDesc, JsonSerializer<?> serializer) {
        return super.modifyMapSerializer(config, valueType, beanDesc, serializer);
    }

}
